let apiConstants = require('../../../api/services/ApiConstants')
let fileServer = 'http://dev-nfs.sf8cloud.com'
let manageServer = "http://localhost:1378";

if( process.env.NODE_ENV === 'production'){
  fileServer = 'https://nfs-src.sf8cloud.com'
  manageServer = "http://admin3.sf8cloud.com"
}else if(process.env.NODE_ENV === 'test'){
  fileServer = 'https://dev-nfs.sf8cloud.com'
  manageServer = "http://t-yundou3.sf8cloud.com"
}

let utils = {
  apiConstants,
  fileServer,
  manageServer
}
utils.phoneReg = /^1[3|4|5|6|7|8|9]\d{9}$|^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/


/**
 * 生成服务器地址
 */
utils.fmtFileUrl=(token,type)=> {
  let prefix = "/receive/";
  if(type=='cover'){
    prefix = "/video/cover/"
  }
  if (token && token.indexOf("EZ-NFS") === 0) {
    return fileServer + prefix + token;
  }
  return token;
}

/**
 * 判断对象为函数
 */
utils.isFunction = fn => {
  return Object.prototype.toString.call(fn) === '[object Function]'
}

/**
 * 函数节流
 */
utils.throttle = (callback, t = 1000) => {
  let ctrl = false

  return function() {
    if (ctrl) return

    ctrl = true
    callback()
    setTimeout(() => {
      ctrl = false
    }, t)
  }
}

/**
 * 是否滑动到底部
 */
utils.isBottom = function(totalHeight,scrollHeight,scrollY) {
  let scrollTop = scrollY||window.scrollY // 已经滚动距离
  let winHeight = totalHeight||window.innerHeight // 屏幕高度
  let docHeight = scrollHeight||(document.documentElement.scrollHeight-scrollY||0) // 可滚动总高度
  let distance = (window.devicePixelRatio || 1)*50
  if (docHeight < winHeight) {
    return false
  }
  if (scrollTop + winHeight < docHeight - distance) {
    return false // 没到底部
  }
  return true // 已到底部
}

/**
 * 从数组中查找满足条件元素的位置
 */
utils.findIndex = function(arr, condition) {
  for (let i = 0, len = arr.length; i < len; i++) {
    if (condition(arr[i])) return i
  }
  return -1
}

utils.calNumberToFloat = function(num,digit,str){
  if(num>digit){
    return (num/digit).toFixed(1)+str;
  }
  return num;
}
//去除所有空格
utils.trimAll = function(s) {
  if (s === "" || s == "" || null == s) {
    return s;
  } else {
    return s.replace(/\s+/g, "");
  }
}
utils.loadSignInfo = function(title,msg,okMethod){
  Vue.prototype.$Modal.info({
    html:'<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 0.42rem 0rem 0rem;">' +
    '<div style="font-size: 0.32rem;font-weight: 600;">'+title+'</div>'+
      '<div style="font-size: 0.28rem;margin-top: 0.6rem;">请打开投影开展活动吧</div>'+
    //'<div style="color: #323232;text-align: center;font-size: 0.3rem;margin: 0.3rem 0.2rem;line-height:0.48rem;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2; -webkit-box-orient: vertical; ">'+msg+'</div>'+
    '</div>',
    showTitle:false,
    width:"5.6rem",
    okText:"知道了",
    closeable:false,
    okStyle: {
      color: '#323232',
      cursor: "pointer",
      fontFamily:'PingFangSC-Bold',
      fontWeight:600,
      fontSize: '0.32rem',
      background:"#fff",
      border:'none',
      marginTop:'0.05rem'
    },
    onOk:()=> {
      if(okMethod){
        location.href=okMethod;
      }
    }
  })
},
utils.commonMsg = function(quote,msg){
  quote.$Message({
      content: msg,
      time: 1500,
      type: "default",
      hasClose: true
    });
  },
/**
 * msg表示提示语，
 * img表示展示的图片
 */
utils.loadModalInfo = function(msg,imgSrc,okMethod){
  if(!imgSrc){
    imgSrc="/images/modal/icon-cuowu.png";
  }
  Vue.prototype.$Modal.info({
    html:'<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 0.42rem 0rem 0rem;">' +
      // '<div><img style="width:0.6rem;height: 0.6rem;" src="'+imgSrc+'"></div>'+
      '<div style="font-size: .32rem;font-family: PingFangSC-Medium, PingFang SC;font-weight: 600;color: #333333;line-height: 0.33rem">提示</div>'+
      '<div style="color: #333;text-align: center;font-size: 0.28rem;font-family: PingFangSC-Medium, PingFang SC;line-height: 0.46rem;margin: 0.36rem 0.2rem 0.7rem;">'+msg+'</div>'+
    '</div>',
    showTitle:false,
    width:"5.6rem",
    okText:"知道了",
    closeable:false,
    okStyle: {
      color: '#323232',
      cursor: "pointer",
      fontFamily:'PingFangSC-Bold',
      fontWeight:600,
      fontSize: '0.32rem',
      background:"#fff",
      border:'none',
      marginTop:'0.05rem'
    },
    onOk:()=> {
      if(!okMethod){
        return;
      }
      if(typeof(okMethod)=="function"){
        return  okMethod();
      }
      location.href=okMethod;
    }
  })
},
  utils.loadConfirmModal = function(msg,okMethod,cancelMethod,okText,desc){
    var imgSrc="/images/login/icon-tixing.png";
    var htmlStr = '<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 0.42rem 0rem 0rem;">';
    if(!desc){
      htmlStr += '<div><img style="width:0.6rem;height: 0.6rem;" src="'+imgSrc+'"></div>';
    }
    htmlStr +='<div style="color:#666;font-size: 0.32rem;line-height: 0.48rem;text-align: center;';
    if(desc){
      htmlStr += 'margin-top: 0.2rem;">'+msg+'</div>';
      htmlStr += '<div style="color:#666;font-size: 0.32rem;line-height: 0.48rem;text-align: center;margin-top: 0.36rem;">'+desc+'</div>';
    }else{
      htmlStr += 'margin-top: 0.36rem;">'+msg+'</div>';
    }
    htmlStr += '</div>';
    Vue.prototype.$Modal.confirm({
      html:htmlStr,
      showTitle:false,
      closeable:false,
      okText:okText||"确定",
      width:"6rem",
      okStyle:{marginLeft:'0.5rem',cursor: "pointer",fontSize:'0.28rem', marginTop:'-0.05rem'},
      onOk:()=> {
        if(!okMethod){
          return;
        }
        if(typeof(okMethod)=="function"){
          return  okMethod();
        }
        location.href=okMethod;
      },
      onCancel:()=>{
        if(!cancelMethod){
          return
        }
        if(typeof(cancelMethod)=="function"){
          return  cancelMethod();
        }
        location.href=cancelMethod;
      }
    })
  },
  utils.loadMessageBoxModal = function(htmlStr,msg,okMethod,cancelMethod,okText,desc){
    Vue.prototype.$Modal.confirm({
      html:htmlStr,
      showTitle:false,
      closeable:false,
      okText:okText||"确定",
      width:"6rem",
      footerStyle:{border:0},
      okStyle:{marginLeft:'0.5rem',cursor: "pointer",fontSize:'0.28rem', marginTop:'-0.05rem'},
      onOk:()=> {
        if(!okMethod){
          return;
        }
        if(typeof(okMethod)=="function"){
          return  okMethod();
        }
        location.href=okMethod;
      },
      onCancel:()=>{
        if(!cancelMethod){
          return
        }
        if(typeof(cancelMethod)=="function"){
          return  cancelMethod();
        }
        location.href=cancelMethod;
      }
    })
  },
  utils.loadSaveModal = function(title,msg,okMethod,cancelMethod,okText){
    Vue.prototype.$Modal.confirm({
        html:'<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 0.42rem 0rem 0rem;">' +
          '<div style="font-size: 0.32rem;font-weight: 600;">'+title+'</div>'+
          '<div style="color: #323232;text-align: center;font-size: 0.3rem;margin: 0.4rem 0.7rem;line-height:0.48rem;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2; -webkit-box-orient: vertical; ">'+msg+'</div>'+
          '</div>',
      showTitle:false,
      closeable:false,
      okText:okText||"取消",
      width:"6rem",
      okStyle:{marginLeft:'0.5rem',cursor: "pointer",fontSize:'0.28rem', marginTop:'-0.05rem'},
      onOk:()=> {
        if(!okMethod){
          return;
        }
        if(typeof(okMethod)=="function"){
          return  okMethod();
        }
        location.href=okMethod;
      },
      onCancel:()=>{
        if(!cancelMethod){
          return
        }
        if(typeof(cancelMethod)=="function"){
          return  cancelMethod();
        }
        location.href=cancelMethod;
      }
    })
  },

/**
 * 提示框（不能关闭）
 */
utils.tipModalInfo = function(msg){
  Vue.prototype.$Modal.info({
    html:'<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;padding: 0.42rem 0.2rem 0rem;">' +
      '<div><img style="width:0.6rem;height: 0.6rem;" src="/images/login/icon-tixing.png"></div>'+
      '<div style="color: #323232;text-align: center;font-size: 0.3rem;line-height: 0.6rem;margin: 0.36rem 0.2rem 0.7rem;">'+msg+'</div>'+
      '</div>',
    showTitle:false,
    closeable:false,
    width:"5.6rem",
    footerStyle:{display:'none'},
    okStyle:{display:'none'},
  })
},

utils.encode = function(text){
  let rawBuffer = Buffer.from(text);
  let base64Str = rawBuffer.toString('base64');
  let base64Buffer = Buffer.from(base64Str,"base64");
  let hex = base64Buffer.toString("hex");
  return hex;
}
utils.showToolbar = function(){
  var agent = navigator.userAgent.toLowerCase();
  var isMiniProgram = (agent.indexOf('micromessenger') >= 0 &&  agent.indexOf("miniprogram") >= 0)
  if(document.referrer&&$("#footerNav").length==0&&isMiniProgram){
    var nav = `<div class="bottomNavArea">
              <div class="arrowArea" onclick="window.history.go(-1)"><span class="leftArrow active" ></span></div>
              <div class="arrowArea" onclick="window.history.go(1);$('.bottomNavArea .rightArrow').removeClass('active')"><span class="rightArrow active" ></span></div>
            </div>`
    $("body").append(nav);
    $("#layout-content").addClass("layoutWithNav");
  }
}
utils.getJsApiTicket = function(){
  axios
    .get(
      '/jsApiTicket?url=' +
      encodeURIComponent(location.href.split('#')[0]) +
      '&rd=' +
      Math.floor(Math.random() * 1000)
    )
    .then(function(data) {
      var config = data.data
      // config.debug = true
      config.jsApiList = [
        'startRecord',
        'stopRecord',
        'onVoiceRecordEnd',
        'playVoice',
        'pauseVoice',
        'stopVoice',
        'onVoicePlayEnd',
        'uploadVoice',
        'downloadVoice',
        'translateVoice',
        'previewImage'
      ]
      wx.config(config)
    })
}
utils.getUrlParam = function(){
  let param = {}

  let urlParamStr = location.search.replace(/^\?|#.*$/g, '')
  if (urlParamStr) {
    let qsParts = urlParamStr.split('&')
    let i, keyAndValue
    for (i = 0; i < qsParts.length; i++) {
      keyAndValue = qsParts[i].split('=')
      param[keyAndValue[0]] = keyAndValue[1]
    }
  }
  return param;
}
module.exports = utils
